package com.itheima.Demo;

import com.itheima.Utils.MybatisUtils;
import com.itheima.dao.UserMapper;
import com.itheima.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;

import java.util.Date;
import java.util.List;

/*
* 使用动态代理对连接的数据库进行操作
* */
public class demo01 {
    //查询 User表
    @Test
    public void Test01(){
        SqlSessionFactory sqlSessionFactory = MybatisUtils.getSqlSessionFactory();//创建工厂对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();//会话对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> l = mapper.findAll();
        l.forEach(user -> System.out.println(user.toString()));
        MybatisUtils.close(sqlSession);
    }
    //增加 一个用户信息
    @Test
    public void Test02(){
        //通过工具包获取工厂对象和 会话对象
        SqlSessionFactory sqlSessionFactory = MybatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //创建一个对象 存放到数据库中
        User user = new User();
        user.setAddress("aa");
        user.setBirthday(new Date());
        user.setSex("女");
        user.setUsername("dale");
        mapper.addUser(user);
        sqlSession.commit();
        //释放资源
        MybatisUtils.close(sqlSession);
    }
    //修改 指定id 用户信息
    @Test
    public void Test03(){
        //通过工具包获取工厂对象和 会话对象
        SqlSessionFactory sqlSessionFactory = MybatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //创建一个对象 存放到数据库中
        User user = new User();
        user.setAddress("无为");
        user.setBirthday(new Date());
        user.setSex("男");
        user.setUsername("黄文龙");
        user.setId(6);
        mapper.updateUser(user);
        //释放资源
        MybatisUtils.close(sqlSession);
    }

    //删除 指定id用户信息
    @Test
    public void Test04(){
        //通过工具包获取工厂对象和 会话对象
        SqlSessionFactory sqlSessionFactory = MybatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(6);
        //释放资源
        MybatisUtils.close(sqlSession);
    }
}
